/*
 * @LastEditors: whitechiina 1293616053@qq.com
 * @LastEditTime: 2023-03-17 17:56:07
 */
// components/BillItem/index.jsx

import React, { useEffect, useState } from 'react';
import { List } from 'zarm';
import PropTypes from 'prop-types';
import dayjs from 'dayjs';
import { useNavigate } from 'react-router-dom'
import CustomIcon from '../CustomIcon';
import { typeMap } from '@/utils';

import s from './style.module.less';

const BillItem = ({ bill }) => {
    const [income, setIncome] = useState(0); // 收入
    const [expense, setExpense] = useState(0); // 支出
    const navigateTo = useNavigate(); // 路由实例

    // 当添加账单是，bill.bills 长度变化，触发当日收支总和计算。
    useEffect(() => {
        // 初始化将传入的 bill 内的 bills 数组内数据项，过滤出支出和收入。
        // pay_type：1 为支出；2 为收入
        // 通过 reduce 累加
        // console.log(bill.bills)
        // const _income = bill.bills.filter(i => i.pay_type == 2).reduce((curr, item) => {
        //     curr += Number(item.amount);
        //     return curr;
        // }, 0);
        // setIncome(_income);
        // const _expense = bill.bills.filter(i => i.pay_type == 1).reduce((curr, item) => {
        //     curr += Number(item.amount);
        //     return curr;
        // }, 0);
        // setExpense(_expense);
    }, [bill.bills]);

    // 前往账单详情
    const goToDetail = (item) => {
        navigateTo(`/detail?id=${item.id}`)
    };

    return <div className={s.item}>
        <div className={s.headerDate}>
            <div className={s.date}>{bill.date}</div>
            <div className={s.money}>
                <span>
                    <img src="//s.yezgea02.com/1615953405599/zhi%402x.png" alt='支' />
                    <span>¥{expense.toFixed(2)}</span>
                </span>
                <span>
                    <img src="//s.yezgea02.com/1615953405599/shou%402x.png" alt="收" />
                    <span>¥{income.toFixed(2)}</span>
                </span>
            </div>
        </div>
        {
            bill.bills?.map((item, index) =>
                <div className={s.bills} key={index}>
                    <div className={s.bill_left}>
                        <div className={s.name}>{item.type_name}</div>
                        <div className={s.remark}>{item.remark} | {dayjs(Number(item.date)).format('HH:mm')}</div>
                    </div>
                    <div className={s.bill_right}>
                        <div className={s.amount}
                        style={{color: item.pay_type ===1? 'green' : 'red'}}
                        >💰{item.pay_type ==1? '-' : '+' }{item.amount}</div>
                    </div>
                </div>
            )
        }
    </div>
};

BillItem.propTypes = {
    bill: PropTypes.object
};

export default BillItem;